﻿
CREATE proc [dbo].[proc_Customer_Delete]
(
	@CustomerId uniqueidentifier,
	@UserName nvarchar(50),
	@DeleteReason nvarchar(50)
)
As	
Begin
	Declare @CustomerName nvarchar(150),@SalesName nvarchar(50),@CreateName nvarchar(50),@ProtectName nvarchar(50)
	Declare @num int,@CompanyId int,@ProtectId int
	
	Select @CustomerName=CustomerName,@ProtectId=ProtectId,@CreateName=CreateName,@ProtectName=ProtectName From Customer Where CustomerId=@CustomerId
	Select @CompanyId=CompanyId From Employee Where UserName=@UserName
	
	if(@ProtectId=2)
		begin
			SET @SalesName=@ProtectName
		end
	else
		begin
			SET @SalesName=@CreateName
		end
	
	Select @num=count(id) from Orders where CustomerId = @CustomerId
	
	if (@num = 0)
	  begin
	   Delete from Customer where CustomerId=@CustomerId
	   Delete From ContactPerson where CustomerId=@CustomerId
	   Delete From Customer_Subjoin_List where CustomerId=Cast(@CustomerId as nvarchar(50))
	   Delete From Customer_Track where CustomerId=@CustomerId
	   Delete From Customer_Remind where CustomerId=Cast(@CustomerId as nvarchar(50))
	  end
	Insert Into Customer_Auditlog(CustomerId,CustomerName,Description,AuditUser,AuditDate,Type,CompanyId,SalesName)
	Values(@CustomerId,@CustomerName,@DeleteReason,@UserName,GetDate(),2,@CompanyId,@SalesName)
End


